import axios from 'axios'
import router from "@/router";


const http = axios.create({
    timeout: 1000 * 30,
    withCredentials: true,
    baseURL: 'http://1.117.66.66:8081/admin',
    headers: {
        'Content-Type': 'application/json; charset=utf-8'
    }
})

/**
 * 请求拦截
 */
http.interceptors.request.use(config => {
    config.headers['Authorization'] = localStorage.getItem('token') // 请求头带上token
    console.log("请求头中的authorization:" + localStorage.getItem('token'));
    return config
}, error => {
    return Promise.reject(error)
})

/**
 * 响应拦截
 */
http.interceptors.response.use(response => {
    // console.log("WWW-Authenticate:" + response.headers['WWW-Authenticate'])
    if (response.data && response.data.code === 401) { // 401, token失效,重新登录
        alert("用户信息异常，请重新登录")
        router.push('/login')
        return //这里的return主要是防止返回登录界面后在弹窗一次alert
    } else {
        let token = response.headers['authorization']
        console.log("响应头中的authorization:" + token);
        if (!(token == null || token === '')) { //后端生成了新的token，并由响应头带给前端
            localStorage.removeItem('token')
            localStorage.setItem('token', token);
        }
    }
    return response
}, error => {

    return Promise.reject(error)
})


export default http
